<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 终端命令执行对象
// +----------------------------------------------------------------------
namespace Inphp\Core\Services\Cmd;

use Inphp\Core\Config;
use Inphp\Core\Middlewares;
use Inphp\Core\Services\IServer;

class Server implements IServer
{
    /**
     * 指令对象
     * @var mixed
     */
    public mixed $commend;

    /**
     *
     */
    public function __construct()
    {
        $argv = $_SERVER['argv'] ?? [];
        if (count($argv) >= 2) {
            $params = count($argv) > 2 ? array_slice($argv, 2) : [];
            if (!empty($params)) {
                $array = [];
                foreach ($params as $param) {
                    $arr = explode("=", $param, 2);
                    $array[$arr[0]] = $arr[1] ?? true;
                    $array[$arr[0]] = $array[$arr[0]]=="true" ? true : ($array[$arr[0]]=="false" ? false : $array[$arr[0]]);
                }
                $params = $array;
            }
            //
            $commend = str_replace(".", "\\", $argv[1]);
            if (class_exists($commend)) {
                //取得中间件列表，先初始化，避免参数未加载
                Middlewares::process("beforeStart", []);
                //初始化指令对象
                $commend = new $commend($params);
                if (method_exists($commend, 'run')) {
                    $this->commend = $commend;
                    return;
                } else {
                    exit("方法不存在：".$commend::class.'->run()'.PHP_EOL);
                }
            }
            exit("指令不存在：".$commend.PHP_EOL);
        }
        exit("未找到要执行的指令".PHP_EOL);
    }

    /**
     * 执行
     */
    public function start(): void
    {
        // TODO: Implement start() method.
        $this->commend->run();
    }
}